package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.CustomerClassDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.CustomerClass;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS11004Srvl
 */
public class CS11004Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private Database db;
	private String vaUrlAddress;
	private String vaAgentBrowser;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS11004Srvl() {
        super();
       
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	
    	String vaProcessType = request.getParameter("process_type");
		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
    	if(vaProcessType.equals("insert")){ 
			insert(request,response);	
		} else if(vaProcessType.equals("edit")){ 
			edit(request , response);
		}else if(vaProcessType.equals("delete")){
			delete(request,response);
		}else if(vaProcessType.equals("update")) {
			update(request,response);
		}else{
			getDataTable(request,response);
		}

    }
    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		this.db = new Database();

		String vnCode = request.getParameter("id");
		
		CustomerClassDAO voCustomerClassDAO = new CustomerClassDAO(db);
		try {
			db.beginTransaction();
			voCustomerClassDAO.deleteCustomerClassByAccount(vnSiteId, vnCode);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11004", JDate.getDate(), JDate.getTime(),vnUserId, "CS11004Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}finally{
			db.close();
		}
		
		response.getWriter().write("Success Data");
		
	}
    public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		

		String vaCodeID =request.getParameter("id");
		String vaDespt =request.getParameter("description");
		String vaOldCutomerClass =request.getParameter("oldCustomerClass");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		CustomerClassDAO voCustomerDAO = new CustomerClassDAO(db);
		String  vaCodeCustomerClass = voCustomerDAO.findsCodeBySiteAndCode(vnSiteId, vaOldCutomerClass, vaCodeID);
		if(vaCodeCustomerClass == null){
			
			CustomerClass poCustomerClass = new CustomerClass();
			poCustomerClass.setVnSiteId(vnSiteId);
			poCustomerClass.setVaCode(vaCodeID);
			poCustomerClass.setVaDescription(vaDespt);
			poCustomerClass.setVnInsertUserId(vnUserId);
			poCustomerClass.setVaUpdateDate(vaDate);
			poCustomerClass.setVaUpdateTime(vaTime);
			
			try {
				db.beginTransaction();
				voCustomerDAO.updateZone(vnSiteId,vaOldCutomerClass, poCustomerClass);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11004", JDate.getDate(), JDate.getTime(),vnUserId, "CS11004Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}finally {
				db.close();
			}
			response.getWriter().write("success data");
				
		}else{
			db.close();
			response.getWriter().write("Code_dupicate");
		}
		
		
    }
    
    public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();

		String vaCodeID =request.getParameter("id");
		String vaDespt =request.getParameter("description");
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();
		
		CustomerClassDAO voCustomerClass = new CustomerClassDAO(db);
		String vaCodeCustomerClass = voCustomerClass.findCodeBySiteAndCode(vnSiteId, vaCodeID);
		if(vaCodeCustomerClass == null){
			
			 CustomerClass poCustomerClass = new CustomerClass();
				poCustomerClass.setVnSiteId(vnSiteId);
				poCustomerClass.setVaCode(vaCodeID);
				poCustomerClass.setVaDescription(vaDespt);
				poCustomerClass.setVnInsertUserId(vnUserId);
				poCustomerClass.setVaInsertDate(vaDate);
				poCustomerClass.setVaInsertTime(vaTime);
		
				try {
					db.beginTransaction();
					voCustomerClass.addCustomerClass(poCustomerClass);
					db.commit();
				} catch (Exception e) {
					SMErrorLogDAO.getInstance().addLog(0, "CS11004", JDate.getDate(), JDate.getTime(),vnUserId, "CS11004Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
					db.rollback();
					e.getMessage();
				}
				response.getWriter().write("Success Data");
				
		}else{
			db.close();
			response.getWriter().write("Code_dupicate");
		}
		
		  
		
    }
    	
    public void getDataTable(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
    	
    	JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		String vaCode = request.getParameter("id");
		
		this.db = new Database();
		CustomerClassDAO  voCusClassDAO = new CustomerClassDAO(db);
		
		List<Map<String , Object>> voListFindAll;
		voListFindAll= voCusClassDAO.findCustomerClassBySiteId(vnSiteId);
		
		for(int i = 0; i < voListFindAll.size() ; i++){ 
			Map<String , Object> mapItem = (Map<String , Object>) voListFindAll.get(i);
			voColumn = new JSONArray();
			voColumn.add(i+1);
			voColumn.add(mapItem.get("CODE"));
			voColumn.add(mapItem.get("DESCRIPTION"));
			voRow.add(voColumn);
		}
		
			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", voListFindAll.size());
			voObject.put("aaData", voRow);
		
			db.close();
			voOut.print(voObject.toJSONString());
    }	

    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		
		this.db = new Database();
		
		PrintWriter  voOut = response.getWriter();
		String vaCodeId = request.getParameter("id");
		int vnSiteId = Integer.parseInt(request.getParameter("siteID"));
		
		CustomerClassDAO voCustomerClassDAO = new CustomerClassDAO(db);
		voCustomerClassDAO.findDescriptionBySiteAndCode(vnSiteId,vaCodeId);
		
		JSONObject jsonobject= new JSONObject();
		jsonobject.put("id",vaCodeId);
		jsonobject.put("desp",voCustomerClassDAO.findDescriptionBySiteAndCode(vnSiteId, vaCodeId));
		
		db.close();
		voOut.print(jsonobject.toJSONString());
    }
    	
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			processRequest(request,response);
		
	}

}
